package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: liuhongfei
 * @create: 2021/11/25 19:08
 */
@Component("connectionUtils")
public class ConnectionUtils {

    /**
     * 创建饿汉式单例的ConnectionUtils
     * 私有化构造方法、初始化静态变量
     */
    // private static ConnectionUtils connectionUtils = new ConnectionUtils();
    //
    // private ConnectionUtils() {
    // }

    // public static ConnectionUtils getInstance() {
    //     return connectionUtils;
    // }
    @Autowired
    private DataSource dataSource;

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getCurrentThreadConnection() throws SQLException {
        Connection currentConn = threadLocal.get();
        if (currentConn == null) {
            currentConn = dataSource.getConnection();
            threadLocal.set(currentConn);
        }
        return currentConn;
    }
}
